package com.breaking.second.activity;

import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.MenuItem;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.viewpager2.widget.ViewPager2;

import com.breaking.second.R;
import com.breaking.second.activity.pager.adapter.FragmentStateAdapter;
import com.breaking.second.activity.pager.home.GoodsPager;
import com.breaking.second.databinding.ActivitySearchBinding;
import com.breaking.second.entity.BookEntity;
import com.breaking.second.entity.GoodsTypeEntity;
import com.breaking.second.utils.StringUtil;
import com.breaking.second.utils.okhttp.OkhttpUtil;
import com.google.android.material.tabs.TabLayout;

import java.util.ArrayList;
import java.util.List;

public class SearchActivity extends BaseActivity<ActivitySearchBinding> implements TabLayout.OnTabSelectedListener , TextWatcher {
    private final List<Fragment> fragments = new ArrayList<>();
    private FragmentStateAdapter fragmentStateAdapter;
    private MenuItem menuItem;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initToolbar();
        initPager();
        initTab();
        initData();
    }

    private void initToolbar() {
        binding.toolbar.setOnMenuItemClickListener(this::OnMenuItemClick);
        menuItem = binding.toolbar.getMenu().findItem(R.id.search);

    }

    private void initTab() {
        binding.editSearch.addTextChangedListener(this);
        binding.tab.addOnTabSelectedListener(this);
    }

    private boolean OnMenuItemClick(MenuItem item) {
        if (item.getTitle() == null) return false;
        if (item.getTitle().equals("搜索")) {
            Fragment fragment = fragments.get(binding.pager.getCurrentItem());
            if (fragment instanceof GoodsPager pagerTeamSearch) {
                Editable editable = binding.editSearch.getText();
                if (StringUtil.isEmpty(editable)) {
                    Toast.makeText(this, "内容不能为空", Toast.LENGTH_SHORT).show();
                    return false;
                }
                String text = editable.toString();
                if (text.length() < 2) {
                    Toast.makeText(this, "搜索不能少于2个关键字", Toast.LENGTH_SHORT).show();
                    return false;
                }
                pagerTeamSearch.search(text);
            }
        } else if (item.getTitle().equals("取消")) {
            finish();
        }
        return false;
    }

    private void initPager() {
        fragmentStateAdapter = new FragmentStateAdapter(getSupportFragmentManager(), getLifecycle(), fragments);
        binding.pager.setAdapter(fragmentStateAdapter);
        binding.pager.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() {
            @Override
            public void onPageSelected(int position) {
                super.onPageSelected(position);
                TabLayout.Tab tab = binding.tab.getTabAt(position);
                if (tab == null) return;
                tab.select();
            }
        });
    }

    private void initData() {
        getTypeData();//初始化分类数据
    }

    private void getTypeData() {
        OkhttpUtil.Get("goods/type", new OkhttpUtil.CallbackListener(this::getTypeData));
    }

    private void getTypeData(BookEntity bookEntity) {
        if (bookEntity.isCode()) {
            List<GoodsTypeEntity> goodsTypeEntities = bookEntity.toList(GoodsTypeEntity.class);
            if (goodsTypeEntities == null) return;
            if (goodsTypeEntities.isEmpty()) return;
            setTabPagerData(goodsTypeEntities);
        }
    }

    private void setTabPagerData(List<GoodsTypeEntity> goodsTypeEntities) {
        binding.tab.removeAllTabs();
        fragmentStateAdapter.notifyItemRangeRemoved(0, fragments.size() + 1);
        fragments.clear();
        for (GoodsTypeEntity entity : goodsTypeEntities) {
            binding.tab.addTab(binding.tab.newTab().setText(entity.getType()));
            fragments.add(new GoodsPager(entity,1));
        }
        fragmentStateAdapter.notifyItemRangeChanged(0, fragments.size());
        binding.pager.setOffscreenPageLimit(fragments.size());
    }

    @Override
    public void onTabSelected(TabLayout.Tab tab) {
        binding.pager.setCurrentItem(tab.getPosition());
    }

    @Override
    public void onTabUnselected(TabLayout.Tab tab) {

    }

    @Override
    public void onTabReselected(TabLayout.Tab tab) {

    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        if (s.length() > 0) {
            // 输入框有文字
            menuItem.setTitle("搜索");
        } else {
            // 输入框为空
            menuItem.setTitle("取消");
        }
    }

    @Override
    public void afterTextChanged(Editable s) {

    }
}
